-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.c
54 lines (43 loc) · 1.2 KB
/
Solution.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>
#include <stdlib.h>
void topologicalSortUtil(int v, int visited[], int *stack, int *top, int graph[][100], int vertices) {
visited[v] = 1;
for (int i = 0; i < vertices; i++) {
if (graph[v][i] && !visited[i]) {
topologicalSortUtil(i, visited, stack, top, graph, vertices);
}
}
stack[++(*top)] = v;
}
void topologicalSort(int graph[][100], int vertices) {
int visited[vertices];
int stack[vertices];
int top = -1;
for (int i = 0; i < vertices; i++) {
visited[i] = 0;
}
for (int i = 0; i < vertices; i++) {
if (!visited[i]) {
topologicalSortUtil(i, visited, stack, &top, graph, vertices);
}
}
printf("Topological Sort: ");
while (top >= 0) {
printf("%d ", stack[top--]);
}
printf("\n");
}
int main() {
int vertices, edges;
printf("Enter the number of vertices and edges: ");
scanf("%d %d", &vertices, &edges);
int graph[100][100] = {0};
printf("Enter the edges (u -> v):\n");
for (int i = 0; i < edges; i++) {
int u, v;
scanf("%d %d", &u, &v);
graph[u][v] = 1;
}
topologicalSort(graph, vertices);
return 0;
}